package com.alphathink.deliveryassist;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.AlphaThink.DeliveryAssist.R;
import com.alphathink.deliveryassist.http.NetOperater;
import com.alphathink.deliveryassist.util.SharePrefUtil;

/**
 * 修改密码
 * 
 * @author click
 * 
 */
public class ChangePwdActivity extends Activity {
	private static String TAG = "ChangePwdActivity";

	private EditText mOldPwdET, mPwdET, mConfirmPwdET;
	private Button mUpdatePwd;
	private SharedPreferences preferences = null;

	private String mOldPwd, mPwd, mComfirmPwd;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_change_pwd);

		initView();
		updatePwd();
	}

	/**
	 * 初始化控件
	 */
	private void initView() {
		preferences = SharePrefUtil.getPref(getApplicationContext());
		Log.d(TAG, "用户名ini--" + preferences.getString(SharePrefUtil.USERNAME, ""));
		mOldPwdET = (EditText) findViewById(R.id.changePwd_oldPwd_EditPwd);

		mPwdET = (EditText) findViewById(R.id.changePwd_updatePwd_EditPwd);

		mConfirmPwdET = (EditText) findViewById(R.id.changePwd_confirmPwd_EditPwd);

		mUpdatePwd = (Button) findViewById(R.id.changePwd_activity_login);

	}

	/**
	 * 修改密码的操作
	 * 
	 */
	private void updatePwd() {
		Log.d(TAG, "用户名up-" + preferences.getString(SharePrefUtil.USERNAME, ""));
		mUpdatePwd.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				mOldPwd = mOldPwdET.getText().toString();
				mPwd = mPwdET.getText().toString();
				mComfirmPwd = mConfirmPwdET.getText().toString();
				Log.d(TAG,
						"用户名--"
								+ preferences.getString(SharePrefUtil.USERNAME,
										""));
				String userName = preferences.getString(SharePrefUtil.USERNAME,
						"");
				if (checkOldPwd() && checkNewPwd()) {
					UpdatePwdAsynTask asynTask = new UpdatePwdAsynTask();
					asynTask.execute(userName, mOldPwd, mComfirmPwd);
				} else if (checkOldPwd() == false) {
					Toast.makeText(getApplication(), "旧密码输入错误！",
							Toast.LENGTH_SHORT).show();
				} else if (checkNewPwd() == false) {
					Toast.makeText(getApplication(), "新密码两次输入不一致",
							Toast.LENGTH_SHORT).show();
				}
			}
		});
	}

	/***
	 * 检验输入的就密码是否正确
	 * 
	 * @return
	 */
	private boolean checkOldPwd() {
		Log.d(TAG, "用户名--" + preferences.getString(SharePrefUtil.USERNAME, ""));
		String mTempOldPwd = preferences.getString(SharePrefUtil.LOGIN_PWD, "");
		Log.d(TAG, "用户名--" + preferences.getString(SharePrefUtil.USERNAME, ""));
		if (mTempOldPwd.equals(mOldPwd)) {
			Log.d(TAG, "验证旧密码－－－－－－－－－－true");
			return true;
		}
		return false;
	}

	/**
	 * 检查新输入的密码是否一致
	 * 
	 * @return
	 */
	private boolean checkNewPwd() {
		if ("".equals(mPwd) || "".equals(mComfirmPwd)) {
			return false;
		} else if (mPwd.equals(mComfirmPwd)) {
			return true;
		}
		return false;

	}

	/**
	 * 生成该类的对象，并调用execute方法之后 首先执行的是onProExecute方法 其次执行doInBackgroup方法
	 * 
	 */
	public class UpdatePwdAsynTask extends AsyncTask<String, Integer, Object> {

		private String mUserName = "";
		private String mPwd = "";
		private String mOld = "";
		private View view = getLayoutInflater().inflate(R.layout.loding_dialog,
				null);
		private AlertDialog.Builder alertDialog = new AlertDialog.Builder(
				ChangePwdActivity.this).setView(view);

		AlertDialog alertDialogs = alertDialog.create();

		public UpdatePwdAsynTask() {

			alertDialogs.getWindow().setType(
					WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
			alertDialogs.setCancelable(false);
			alertDialogs = alertDialog.show();
		}

		@Override
		protected Object doInBackground(String... params) {
			// parmas->0:username;1:password
			mUserName = params[0];
			mOld = params[1];
			mPwd = params[2];
			String host = preferences.getString(SharePrefUtil.UPDATEPWD_URL,
					SharePrefUtil.UPDATEPWD_URL);
			NetOperater netOperator = new NetOperater();
			// 获取到后台返回的数据存储在一个string中，
			String str = netOperator
					.operaterNetUpdatePwd(mUserName, mPwd, mOld,host);

			Log.d(TAG, "====Login时doInBackground中返回的string类型的参数====" + "/n");
			return str;
		}

		/**
		 * 这里的String参数对应AsyncTask中的第三个参数（也就是接收doInBackground的返回值）
		 * 在doInBackground方法执行结束之后在运行，并且运行在UI线程当中 可以对UI空间进行设置
		 */
		@Override
		protected void onPostExecute(Object result) {

			System.out.println("====student====" + result);

			// 如果this.isCancelled等于true这取消操作
			if (this.isCancelled()) {
				return;
			}
			if (result == null) {
				alertDialogs.cancel();

				Log.v(TAG, "onPostExecute-->基本上是解析出错．或者网络错误");
				return;
			}

			// 将String result强制转换成LoginNetModel

			/**
			 * 200 请求成功 400 未知错误 401 用户名不存在 402 密码错误 500 服务器内部错误 404 参数不完整
			 * 
			 */
			if ("true".equals(result)) {
				alertDialogs.cancel();
				SharedPreferences.Editor editor = preferences.edit();
				editor.putString(SharePrefUtil.LOGIN_PWD, mComfirmPwd);
				editor.commit();
				Log.d(TAG,
						"修改之后的密码---"
								+ preferences.getString(
										SharePrefUtil.LOGIN_PWD, ""));
				Log.d(TAG,
						"用户名--"
								+ preferences.getString(SharePrefUtil.USERNAME,
										""));
				Toast.makeText(getApplication(), "密码修改成功，将在３秒后跳转到登陆界面!",
						Toast.LENGTH_SHORT).show();

				// ClearCache.cleanExternalCache(getApplicationContext());
				// ClearCache.cleanInternalCache(getApplicationContext());
				Log.d(TAG, "密碼緩存修改完毕,即将跳转到登陆界面");
				new Handler().postDelayed(new Runnable() {
					@Override
					public void run() {
						Intent intent = new Intent();
						intent.setClass(ChangePwdActivity.this,
								LoginActivity.class);
						startActivity(intent);
					}
				}, 3000);
			} else {
				alertDialogs.cancel();
				// 这里是其他情况．自己进行判断处理
				Toast.makeText(getApplicationContext(), "用户名密码出错！",
						Toast.LENGTH_SHORT).show();
			}
		}

		// 该方法运行在UI线程当中,并且运行在UI线程当中 可以对UI空间进行设置
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		/**
		 * 这里的Intege参数对应AsyncTask中的第二个参数
		 * 在doInBackground方法当中，，每次调用publishProgress方法都会触发onProgressUpdate执行
		 * onProgressUpdate是在UI线程中执行，所有可以对UI空间进行操作
		 */
		// 运行中变动代码
		@Override
		protected void onProgressUpdate(Integer... values) {

		}

	}
}
